from datetime import datetime

from exts import db
from response import Response


class BorrowRecord(db.Model):
    __tablename__ = 'borrowrecord'
    record_id = db.Column('recordId', db.Integer, primary_key=True, autoincrement=True)
    person_id = db.Column('personId', db.Integer, db.ForeignKey('person.personId'), nullable=False)
    book_id = db.Column('bookId', db.Integer, db.ForeignKey('book.bookId'), nullable=False)
    borrow_date = db.Column('borrowDate', db.DateTime, default=datetime.now())
    return_date = db.Column('returnDate', db.DateTime)

    def to_dict(self):
        return {
            'record_id': self.record_id,
            'person_id': self.person_id,
            'book_id': self.book_id,
            'borrow_date': self.borrow_date.strftime('%Y-%m-%d %H:%M:%S'),
            'return_date': self.return_date.strftime('%Y-%m-%d %H:%M:%S') if self.return_date else None,
            '_links': self.get_link()

        }

    def get_link(self):
        return {
            'self': 'http://localhost:3000/records/{}'.format(self.record_id),
            'person': 'http://localhost:3000/persons/{}'.format(self.person_id),
            'book': 'http://localhost:3000/books/{}'.format(self.book_id)
        }

    @staticmethod
    def get_records():
        try:
            records = BorrowRecord.query.all()
            records_list = [record.to_dict() for record in records]
            data = {
                'records': records_list,
                '_links': {
                    'self': 'http://localhost:3000/records'}
            }
            return Response.make_response(data=data, message='获取记录成功！')
        except Exception as e:
            db.session.rollback()
            return Response.make_response(status='500', message=str(e))

    @staticmethod
    def add_record(book_id, person_id):
        record = BorrowRecord(book_id=book_id, person_id=person_id, borrow_date=datetime.now())
        try:
            db.session.add(record)
            db.session.commit()
            data = {
                '_links': {
                    'self': 'http://localhost:3000/records/{}'.format(record.record_id)}
            }
            return Response.make_response(data=data, message='新借用记录添加成功！')
        except Exception as e:
            db.session.rollback()
            return Response.make_response(status='500', message=str(e))

    @staticmethod
    def update_record(record_id):
        try:
            record = BorrowRecord.query.get(record_id)
            if record is not None:
                record.return_date = datetime.now()
                db.session.commit()
                data = {
                    '_links': {
                        'self': 'http://localhost:3000/records/{}'.format(record.record_id)}
                }
                return Response.make_response(data=data, message='借用记录更新成功！')
            else:
                return Response.make_response(status='404', message='未查询到账户！')
        except Exception as e:
            db.session.rollback()
            return Response.make_response(status='500', message=str(e))

    @staticmethod
    def delete_record(record_id):
        try:
            record = BorrowRecord.query.get(record_id)
            if record is not None:
                    db.session.delete(record)
                    db.session.commit()
                    data = {
                        '_links': {
                            'self': 'http://localhost:3000/records/{}'.format(record.record_id)
                        }
                    }
                    return Response.make_response(data=data, message='借阅记录删除成功！')
            else:
                return Response.make_response(status='404', message='未查询到借阅记录！')
        except Exception as e:
            db.session.rollback()
            return Response.make_response(status='500', message=str(e))
